#include <iostream>

#include "UdpClient.hpp"

using namespace UdpClientArea;

int main(int argc, char *argv[])
{
    //需要传服务器的ip地址以及端口号
    if (argc != 3)
    {
        LOG(LogLevel::ERROR) << "Usage error,argc should be 3";
        DIE(USAGE_ERROR);
    }

    // 获取服务器 ip地址 和 端口号
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    //创建socket
    int socketfd = ::socket(AF_INET,SOCK_DGRAM,0);
    if(socketfd<0)
    {
        LOG(LogLevel::ERROR)<<"socket error";
        DIE(SOCKET_ERROR);
    }

    //填充服务器信息
    struct sockaddr_in server;
    bzero(&server,sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = ::htons(serverport);
    server.sin_addr.s_addr = ::inet_addr(serverip.c_str());

    while(true)
    {
        std::cout<<"Please Enter# ";
        std::string message;
        std::getline(std::cin,message);

        ssize_t n = ::sendto(socketfd,message.c_str(),message.size(),0,CONV(&server),sizeof(server));
        if(n<0)
        {
            LOG(LogLevel::ERROR)<<"sendto srror";
            DIE(SENDTO_ERROR);
        }

        //用于 recvfrom 存放发送数据源地址的信息
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        memset(&temp,0,sizeof(temp));
        char buffer[1024];

        ssize_t size = ::recvfrom(socketfd,buffer,sizeof(buffer)-1,0,CONV(&temp),&len);
        if(size>0)
        {
            buffer[size] = 0;
            std::cout<<buffer<<std::endl;
        }
    }

    return 0;
}